<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-12-21
 * Time: 下午2:07
 */

namespace api\modules\e_divide\controllers;


use common\components\e_divide\Config;
use common\components\e_divide\EDivide;
use common\components\tools\FileHelper;
use common\components\tools\Model;
use common\components\tools\Tools;
use common\models\EdiviCommonBackLogs;
use common\models\EdiviCreditOrder;
use common\models\EdiviCreditOrderUsers;
use common\models\EdiviOrderSendLogs;
use wodrow\yii\rest\ApiException;
use wodrow\yii\rest\Controller;
use GuzzleHttp\Client;
use yii\db\Exception;

class DefaultController extends Controller
{
    /**
     * 征信
     * @desc get/post
     * @param string $json 征信数据
     * @param string $other_data 其他数据
     * @return array|mixed
     * @throws
     */
    public function actionCredit($json, $other_data = null)
    {
        $data = json_decode($json, true);
        $edivi = new EDivide();
        $r = $edivi->credit($data);
        return $r;
    }

    /**
     * 验签征信
     * @desc get/post
     * @param string $json 数据
     * @param string $other_data 其他数据
     * @return array|mixed
     * @throws
     */
    public function actionCreditConfirm($json, $other_data = null)
    {
        $data = json_decode($json, true);
        $edivi = new EDivide();
        $r = $edivi->creditConfirm($data);
        return $r;
    }

    /**
     * 开卡
     * @desc /get/post
     * @param string $json 开卡数据
     * @param string $other_data 其他数据
     * @throws
     */
    public function actionGenerateCard($json, $other_data = null)
    {
        $data = json_decode($json, true);
        $edivi = new EDivide();
        $r = $edivi->generateCard($data);
        return $r;
    }

    /**
     * 分期
     * @desc /get/post
     * @param string $json 开卡数据
     * @param string $other_data 其他数据
     * @throws
     */
    public function actionDivi($json, $other_data = null)
    {
        $data = json_decode($json, true);
        $edivi = new EDivide();
        $r = $edivi->divi($data);
        return $r;
    }

    /**
     * 押品补录
     * @desc /get/post
     * @param string $json 数据
     * @param string $other_data 其他数据
     * @throws
     */
    public function actionYpbl($json, $other_data = null)
    {
        $data = json_decode($json, true);
        $edivi = new EDivide();
        $r = $edivi->ypbl($data);
        return $r;
    }

    /**
     * 材料补录
     * @desc /get/post
     * @param string $json 数据
     * @param string $other_data 其他数据
     * @throws
     */
    public function actionClbl($json, $other_data = null)
    {
        $data = json_decode($json, true);
        $edivi = new EDivide();
        $r = $edivi->clbl($data);
        return $r;
    }

    /**
     * 获取e分期订单信息
     * @desc get/post
     * @param string $order_no
     * @return array
     * @return array edivi_o e分期信息
     * @throws
     */
    public function actionOrderInfo($order_no)
    {
        $edivi_o = EdiviCreditOrder::find()->select(['id', 'estage_order_no', 'status'])->where(['order_no' => $order_no])->one();
        $edivi = new EDivide();
        $r = $edivi->orderInfo($order_no);
        $r['edivi_o'] = $edivi_o->toArray();
        return $r;
    }

    /**
     * 获取用户e分期操作记录
     * @desc get/post
     * @param string $idcard 身份证
     * @param string $orderno 订单号
     * @param string $e_orderno E分期订单号
     * @return array
     */
    public function actionUserLog($idcard = null, $orderno = null, $e_orderno = null)
    {
        $log = [];
        $query = EdiviCreditOrder::find();
        if (!$idcard && !$orderno && !$e_orderno){
            throw new ApiException(201907031408, "必须至少一个查询参数");
        }
        if ($idcard){
            $users = EdiviCreditOrderUsers::find()->where(['id_card' => $idcard])->all();
        }
        if ($orderno){
            $query->where(['order_no' => $orderno]);
            $credit = $query->one();
            $users = $credit->ediviCreditOrderUsers;
        }
        if ($e_orderno){
            $query->where(['estage_order_no' => $e_orderno]);
            $credit = $query->one();
            $users = $credit->ediviCreditOrderUsers;
        }
        foreach ($users as $k => $v){
            $x = [
                'edivi_order_id' => $v->edivi_credit_order_id,
                'user_name' => $v->user_name,
                'id_card' => $v->id_card,
                'order_no' => $v->ediviCreditOrder->order_no,
                'estage_order_no' => $v->ediviCreditOrder->estage_order_no,
            ];
            $credit = $v->ediviCreditOrder;
            $x['last_status'] = $v->ediviCreditOrder->status;
            $x['send_logs'] = [];
            foreach ($credit->ediviOrderSendLogs as $k1 => $v1){
                $x['send_logs'][] = [
                    '_b_code' => EDivide::getBCodes()[$v1->b_code],
                    '_created_at' => date("Y-m-d H:i:s", $v1->created_at),
                    'to_api_data' => json_decode($v1->to_api_data, true),
                ];
            }
            $x['back_logs'] = [];
            foreach ($credit->ediviCommonBackLogs as $k2 => $v2){
                $x['back_logs'][] = [
                    'trans_type' => $v2->trans_type,
                    '_trans_type' => EdiviCommonBackLogs::getTransTypes()[$v2->trans_type],
                    '_created_at' => date("Y-m-d H:i:s", $v2->created_at),
                    'opinion' => $v2->opinion,
                ];
            }
            $log[] = $x;
        }
        return $log;
    }

    /**
     * 订单申请
     * @desc /get/post 示例{"orderNo":"155963","applyType":"2","applyReason":"test","applyName":"测试"}其中applyType:2-取消订单申请  3-撤销取消订单申请
     * @param string $json 数据
     * @param string $other_data 其他数据
     * @throws
     */
    public function actionOrderApply($json, $other_data = null)
    {
        $data = json_decode($json, true);
        $edivi = new EDivide();
        $r = $edivi->orderApply($data);
        return $r;
    }

    /**
     * 面签报告
     * @param string $clientName 客户姓名
     * @param string $clientIdCard 客户身份证
     * @param null|string $deptCode 报告订单号（deptCode、signOn、orderNo参数三选一，传此参数表示取该机构下该面签人最新一次面签记录。
     * @param null|string $signOn 报告订单号（deptCode、signOn、orderNo参数三选一）
     * @param null|string $orderNo 报告订单号（deptCode、signOn、orderNo参数三选一，传此参数表示取该外部订单下该面签人最新一次面签记录。）
     * @throws
     */
    public function actionFaceValidateReport($clientName, $clientIdCard, $deptCode = null, $signOn = null, $orderNo = null)
    {
        $form_params = [
            'clientName' => $clientName,
            'clientIdCard' => $clientIdCard,
        ];
//        if ($deptCode){
//            $form_params['deptCode'] = $deptCode;
//        }
//        if ($signOn){
//            $form_params['signOn'] = $signOn;
//        }
//        if ($orderNo){
//            $form_params['orderNo'] = $orderNo;
//        }
        $edivi = new EDivide();
        if (!$orderNo){
            throw new ApiException(201908191418, "必须要有订单号");
        }
        $edivi_c = EdiviCreditOrder::findOne(['order_no' => $orderNo]);
        if (!$edivi_c){
            throw new ApiException(201908191419, "没有找到订单");
        }
        $bankCode = $edivi_c->bank_code;
        $conf = $edivi->getConf($bankCode);
        $client = new Client([
            'base_uri' => $conf['face_validate_uri'],
        ]);
        $resp = $client->request('POST', '', [
            'form_params' => $form_params,
        ]);
        $_contents = $resp->getBody()->getContents();
        $contents = json_decode($_contents, true);
        if (!isset($contents['code']) || $contents['code'] != 0){
            throw new ApiException($contents['code'], $contents['msg']);
//            throw new ApiException(201904281413, $_contents);
        }
        return $contents['data'];
    }

    /**
     * 面签报告word
     * @param string $type
     * @param null|string $signOn 报告订单号（deptCode、signOn、orderNo参数三选一）
     * @throws
     */
    public function actionFaceValidateReportWord($signOn = null, $type = 2)
    {
        $form_params = [
            'signOn' => $signOn,
            'type' => $type,
        ];
        $edivi = new EDivide();
        $edivi_c = EdiviCreditOrder::findOne(['order_no' => $signOn]);
        if (!$edivi_c){
            throw new ApiException(201908191420, "没有找到订单");
        }
        $bankCode = $edivi_c->bank_code;
        $conf = $edivi->getConf($bankCode);
        $client = new Client([
            'base_uri' => $conf['face_validate_word_uri'],
        ]);
        $resp = $client->request('POST', '', [
            'form_params' => $form_params,
        ]);
        $_contents = $resp->getBody()->getContents();
        $contents = json_decode($_contents, true);
        if (!isset($contents['code']) || $contents['code'] != 0){
            throw new ApiException(201904281414, $_contents);
        }
        return $contents;
    }

    /**
     * 3.10 订单通知记录查询
     * @desc 3.10 订单通知记录查询
     * @param string $json 示例{"orderNo":"", "bankCode":""}
     * @param string $other_data
     * @return array
     * @throws
     */
    public function actionCheckOrderNoticeLog($json, $other_data = null)
    {
        $data = json_decode($json, true);
        $edivi = new EDivide();
        $r = $edivi->checkOrderNoticeLog($data);
        return $r;
    }

    /**
     * 补查关联人
     * @desc 详见补查关联人接口,非电子签约类订单无需对接此接口。
     * @param string $json 示例{"orderNo":"", "bankCode":"", "spouse":{...}}
     * @param string $other_data
     * @return array
     * @throws
     */
    public function actionCompensationAssociates($json, $other_data = null)
    {
        $data = json_decode($json, true);
        $edivi = new EDivide();
        $r = $edivi->compensationAssociates($data);
        return $r;
    }

    /**
     * 3.7电子签约合同与证据链下载
     * @desc 机构方视情况对接此功能
     * @param string $json 示例{"orderNo":"", "bankCode":"", "filename":null}
     * @param string $other_data
     * @return array
     * @throws
     */
    public function actionDownloadHtZjl($json, $other_data = null)
    {
        $busiCode = EDivide::B_CODE_HT_DOWNLOAD;
        $edivi = new EDivide();
        $data = json_decode($json, true);
        $orderNo = $data['orderNo'];
        if (!$orderNo){
            throw new ApiException(201907221051, "必须要有订单号");
        }
        $edivi_c = EdiviCreditOrder::findOne(['order_no' => $orderNo]);
        if (!$edivi_c){
            throw new ApiException(201907221052, "没有找到订单");
        }
        $bankCode = $edivi_c->bank_code;
        $conf = $edivi->getConf($bankCode);
        if (isset($data['filename'])&&$data['filename']){
            $filename = $data['filename'];
        }else{
            $filename = "HtZjl_".$orderNo.".zip";
        }
        $sink = \Yii::getAlias('@uploads_root/e_divide/'.$filename);
        if (!is_dir(dirname($sink))){
            FileHelper::createDirectory(dirname($sink));
        }
        $edivi_c = EdiviCreditOrder::findOne(['order_no' => $data['orderNo']]);
        if (!$edivi_c){
            throw new ApiException(201907091320, "没有找到订单");
        }
        $params = [
            "assurerNo" => $conf['assurerNo'],
            "platNo" => $conf['platNo'],
            "busiCode" => $busiCode,
            'bankType' => $conf['bankType'],
            "bankCode" => $bankCode,
            "orderNo" => $orderNo,
            "productType" => $conf['productType'],
        ];
        $_params = [];
        foreach ($params as $k => $v){
            $_params[] = $k."=".$v;
        }
        $url = $conf['base_output_uri']."?".Tools::arr2str($_params, "&");
        return [
            'url' => $url,
        ];
        /*$client = new Client();
        $resp = $client->request('GET', Config::$base_output_uri, [
            'query' => $params,
            'sink' => $sink,
        ]);
        $cont = $resp->getBody()->getContents();
        $_cont = json_decode($cont, true);
        if (!$cont||!$_cont||!isset($_cont['code'])||$_cont['code'] != 0){
            throw new ApiException(201907221049, $cont);
        }
        $log = new EdiviOrderSendLogs();
        $log->edivi_credit_order_id = $edivi_c->id;
        $log->b_code = EDivide::B_CODE_HT_DOWNLOAD;
        $log->to_api_data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $log->ed_data = json_encode($params, JSON_UNESCAPED_UNICODE);
        $log->to_ed_data = json_encode($params, JSON_UNESCAPED_UNICODE);
        $log->ed_resp_code = (string)$_cont['code'];
        $log->ed_resp_data = json_encode($_cont, JSON_UNESCAPED_UNICODE);
        $log->created_at = time();
        if (!$log->save()){
            throw new Exception(Model::getModelError($log));
        }
        return [
            'plat_resp' => $_cont,
            'log' => $log->toArray(),
        ];*/
    }
}